package com.fhnew.app.model.internet.model;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.fhnew.app.model.internet.HttpAPI;
import com.fhnew.app.model.internet.been.B_Login;
import com.fhnew.app.model.internet.been.B_UserMoney;
import com.fhnew.app.model.internet.been.Been;
import com.fhnew.app.util.HLog;
import com.fhnew.app.util.SpUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户数据统一管理
 */
public class UserModel {

    private static final String LOGINING = "loging";
    private static final String USER_NAME = "username";
    private static final String USER_PASSWORD = "password";
    private static final String FILE_NAME = "cookies";
    private static final String SAVE_PASSWORD = "savePassword";
    private static final String TOKEN = "token";
    private static final String ROOT_URL = "root_url";

    private static UserModel userModel;

    private boolean isLogin = false;
    private String userName  = null;
    private String userPassword = null;
    private String cookie = null;
    private boolean savePassword = false; // 表示是否自动填入密码
    private String token = null;
    private String rootUrl = null;
    public B_Login.DataBean mUser;

    private Context context;

    //用于兼容以前的代码
    public static B_Login.DataBean user;//用户信息
    public static String Token;//token

    /**
     * @param context
     *      由于每次使用时都需要传如context，所以这里的context调用不会出现内存泄露
     * @return
     */
    public static UserModel getInstance(Context context){
        if(userModel == null){
            userModel = new UserModel(context);
        }
        return userModel;
    }

    private UserModel (Context context){
        this.context = context;
        listeners = new ArrayList<>();

        isLogin = SpUtils.getBoolean(context,LOGINING);

        userName = SpUtils.getString(context,USER_NAME);
        userPassword =  SpUtils.getString(context,USER_PASSWORD);
        savePassword = SpUtils.getBoolean(context,SAVE_PASSWORD);

        cookie = SpUtils.getString(context,FILE_NAME);
        token = SpUtils.getString(context,TOKEN);

        rootUrl = SpUtils.getString(context,ROOT_URL);
    }

    /**
     * 登录
     * @param user
     */
    public void login (B_Login.DataBean user) {
        mUser = user;
        setToken(mUser.getToken());

        UserModel.user = user;
        UserModel.Token = user.getToken();

        isLogin = true;
        SpUtils.putBoolean(context,LOGINING,isLogin);
        notifyChange();
    }

    /**
     * 退出登录
     */
    public void loginOut(){
        SpUtils.putBoolean(context,LOGINING,isLogin);
        mUser = null;
        this.token = "";
        SpUtils.putString(context,TOKEN,token);

        SpUtils.putBoolean(context,LOGINING,false);
        SpUtils.putString(context,USER_NAME,"");
        SpUtils.putString(context,USER_PASSWORD,"");
        SpUtils.putString(context,FILE_NAME,"");

        SpUtils.putBoolean(context,SAVE_PASSWORD, false);
        SpUtils.putString(context,TOKEN,"");

        isLogin = false;
        notifyChange();
    }

    public boolean isLogin () {
        return isLogin;
    }

    /**
     * 保存账户密码
     * @param userName
     * @param userPassword
     * @param savePassword
     */
    public void setUserLoginStatus(String userName,String userPassword,boolean savePassword){
        setSavePassword(savePassword);
        setUserName(userName);
        setUserPassword(userPassword);
    }

    /**
     * 缓存登出
     */
    public static Been loginStatusCheck(Been been){
        if(been.getCode() == 600||been.getCode() == 400){
            HLog.I("退出状态退出 ==============================");
            userModel.handler.sendEmptyMessage(0x001);
            return null;
        }
        return been;
    }

    //=====================================================================================
    // 观察者相关函数
    //     注意：使用观察者监听用户数据变化需要注销监听
    //=====================================================================================

    private List<UserInformationChanged> listeners;

    private void notifyChange(){
        for (int i = 0; i < listeners.size(); i++) {
            listeners.get(i).userInformationChanged();
        }
    }

    public void registListener(UserInformationChanged userInformationChanged){
        listeners.add(userInformationChanged);
    }

    public void unRegistListener(UserInformationChanged userInformationChanged){
        listeners.remove(userInformationChanged);
    }

    public interface UserInformationChanged{
        public void userInformationChanged ();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage (Message msg) {
            super.handleMessage(msg);
            userModel.loginOut();
        }
    };

    //=====================================================================================
    // Get和Set函数
    //=====================================================================================



    public boolean getSavePassword () {
        return savePassword;
    }

    private void setSavePassword (boolean savePassword) {
        this.savePassword = savePassword;
        SpUtils.putBoolean(context,SAVE_PASSWORD, savePassword);
        notifyChange();
    }

    public String getUserName () {
        return userName;
    }

    private void setUserName (String userName) {
        this.userName = userName;
        if(savePassword)
            SpUtils.putString(context,USER_NAME,userName);
        notifyChange();
    }

    public String getUserPassword () {
        return userPassword;
    }

    private void setUserPassword (String userPassword) {
        this.userPassword = userPassword;
        if(savePassword)
            SpUtils.putString(context,USER_PASSWORD,userPassword);
        notifyChange();
    }

    public String getCookie () {
        return cookie;
    }

    public void setCookie (String cookie) {
        this.cookie = cookie;
        SpUtils.putString(context,FILE_NAME,cookie);
        notifyChange();
    }

    public String getToken () {
        return token;
    }

    private void setToken (String token) {
        this.token = token;
        SpUtils.putString(context,TOKEN,token);
        notifyChange();
    }

    public String getRootUrl () {
        return rootUrl;
    }

    public void setRootUrl (String rootUrl) {
        this.rootUrl = rootUrl;
        SpUtils.putString(context,ROOT_URL,rootUrl);
        notifyChange();
    }

    public B_Login.DataBean getUser () {
        return mUser;
    }

}
